import React, {Component} from 'react';
import {
  ActivityIndicator,
  Linking,
  PermissionsAndroid,
  RefreshControl,
  Text,
  View,
  NativeModules,
  Platform
} from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';
import {BASE_URL} from '../common/BASE_URL';
// import HttpUtils from '../expand/dao/HttpUtils';
import GlobalStyles from '../common/styles/GlobalStyles';
import {StylesConstant} from '../common/Constant';
import {Modal} from '@ant-design/react-native';
import ToastUtil from './ToastUtil';
import AntDesign from 'react-native-vector-icons/AntDesign';
import RNLocation from 'react-native-location';

let x_PI = (3.14159265358979324 * 3000.0) / 180.0;
let PI = 3.1415926535897932384626;
let a = 6378245.0;
let ee = 0.00669342162296594323;
const GDKEY = '0e8baf4222242868742a8e22627d937e'
export default class Utils {
  static async getLocation(){
      return new Promise((resolve, reject) => {
          RNLocation.configure({
              distanceFilter: 5.0,
          });
          RNLocation.requestPermission({
              ios: 'whenInUse',
              android: {
                  detail: 'coarse',
              },
          }).then((granted) => {
              if (granted) {
                  RNLocation.getLatestLocation({
                      timeout: 6000,
                  }).then((res) => {
                      // console.log(res);
                      // let PI = 3.1415926535897932384626; // let a = 6378245.0; // let ee = 0.00669342162296594323;
                      const {longitude, latitude} = res;
                      let dlat = this.transformlat(longitude - 105.0, latitude - 35.0);
                      let dlng = this.transformlng(longitude - 105.0, latitude - 35.0);
                      let radlat = (latitude / 180.0) * PI;
                      let magic = Math.sin(radlat);
                      magic = 1 - ee * magic * magic;
                      let sqrtmagic = Math.sqrt(magic);
                      dlat = (dlat * 180.0) / (((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
                      dlng = (dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
                      let mglat = latitude + dlat;
                      let mglng = longitude + dlng;
                      // console.log(mglng);
                      // console.log(mglat);
                      fetch(`http://restapi.amap.com/v3/geocode/regeo?key=${GDKEY}&location=${mglng},${mglat}&radius=1000&extensions=all&batch=false&roadlevel=0`, {
                          method: "POST",
                          headers: {
                              "Content-Type": "application/x-www-form-urlencoded"
                          },
                          body: ``
                      })
                          .then((response) => response.json())
                          .then((jsonData) => {
                              try {
                                  const {addressComponent, formatted_address} = jsonData.regeocode
                                  // console.log(jsonData.regeocode.addressComponent)
                                  // console.log(jsonData.regeocode.formatted_address)
                                  // {"info": "OK", "infocode": "10000",
                                  //     "regeocode": {
                                  //     "addressComponent": {
                                  //         "adcode": "510107", "building": [Object], "businessAreas": [Array], "city": "成都市", "citycode": "028", "country": "中国", "district": "武侯区", "neighborhood": [Object], "province": "四川省", "streetNumber": [Object], "towncode": "510107064000", "township": "桂溪街道"}, "aois": [[Object]], "formatted_address": "四川省成都市武侯区桂溪街道吉泰路43号朗基·天香(天府五街)", "pois": [[Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object], [Object]], "roadinters": [[Object]], "roads": [[Object], [Object], [Object]]}, "status": "1"}
                                  resolve({
                                      addressComponent,
                                      formattedAddress: formatted_address
                                  })
                              }catch (e) {
                                  // console.log(e)
                                  reject(null)
                              }
                          })
                          .catch((error) => {
                              // console.error(error);
                              reject(null)
                          })
                  });
              }
          });
      });


  }
  static transformlat(lng, lat) {
      let ret =
          -100.0 +
          2.0 * lng +
          3.0 * lat +
          0.2 * lat * lat +
          0.1 * lng * lat +
          0.2 * Math.sqrt(Math.abs(lng));
      ret +=
          ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
              2.0) /
          3.0;
      ret +=
          ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) /
          3.0;
      ret +=
          ((160.0 * Math.sin((lat / 12.0) * PI) +
              320 * Math.sin((lat * PI) / 30.0)) *
              2.0) /
          3.0;
      return ret;
  }
  static transformlng(lng, lat) {
      let ret =
          300.0 +
          lng +
          2.0 * lat +
          0.1 * lng * lng +
          0.1 * lng * lat +
          0.1 * Math.sqrt(Math.abs(lng));
      ret +=
          ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) *
              2.0) /
          3.0;
      ret +=
          ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) /
          3.0;
      ret +=
          ((150.0 * Math.sin((lng / 12.0) * PI) +
              300.0 * Math.sin((lng / 30.0) * PI)) *
              2.0) /
          3.0;
      return ret;
  }
  /**
   * 通过文件后缀判断是否为图片
   */
  static checkImage(fileName = '') {
    fileName = fileName.toLowerCase();
    if (!fileName) {
      return false;
    }
    if (
      fileName.indexOf('png') !== -1 ||
      fileName.indexOf('jpg') !== -1 ||
      fileName.indexOf('jpeg') !== -1 ||
      fileName.indexOf('gif') !== -1 ||
      fileName.indexOf('.bmp') !== -1 ||
      fileName.indexOf('icon') !== -1
    ) {
      return true;
    }
    return false;
  }
  /**
   * 根据文件后缀返回文件图标
   * @param fileName
   */
  static renderFileIcon(fileName, color = '#4CBAFC') {
    fileName = fileName.toLowerCase();
    let icon = 'file1';
    if (fileName.indexOf('.docx') !== -1 || fileName.indexOf('.doc') !== -1) {
      icon = 'wordfile1';
    } else if (
      fileName.indexOf('.xlsx') !== -1 ||
      fileName.indexOf('.xls') !== -1
    ) {
      icon = 'exclefile1';
    } else if (fileName.indexOf('.pdf') !== -1) {
      icon = 'pdffile1';
    } else if (
      fileName.indexOf('.ppt') !== -1 ||
      fileName.indexOf('.pptx') !== -1
    ) {
      icon = 'pptfile1';
    } else if (
      fileName.indexOf('.png') !== -1 ||
      fileName.indexOf('.jpg') !== -1 ||
      fileName.indexOf('.jpeg') !== -1 ||
      fileName.indexOf('.gif') !== -1 ||
      fileName.indexOf('.bmp') !== -1 ||
      fileName.indexOf('.icon') !== -1
    ) {
      icon = 'jpgfile1';
    }
    return (
      <AntDesign
        style={{paddingRight: 7}}
        name={icon}
        size={20}
        color={color}
      />
    );
  }
  /**
   *  打开浏览器下载附件
   * @param url 文件真实全地址
   */
  static openBrowserDownloadFile(url, name = '') {
    // 判断系统
    if (Platform.OS === 'ios') {
      // NativeModules.DownloadFile.downloading(url, name, name);
      // console.log(NativeModules.CalendarModule);
      // NativeModules.CalendarModule.findEvents((a,b)=>{
      //   console.log(a, b);
      // });
      // console.log(NativeModules.PreviewDownloadFile);
      // console.log(url);
      Modal.alert('提示', '确认预览/下载附件？', [
        {
          text: '取消',
          // onPress: () => console.log('cancel'),
          style: 'cancel',
        },
        {
          text: '确认',
          onPress: () => {
            Linking.openURL(url);
          },
        },
      ]);
      return;
    }
    Linking.canOpenURL('KingsoftOfficeApp://').then((supported) => {
      if (!supported) {
        // ToastUtil.info('KingsoftOfficeApp: 请先安装 xxx App');
        Modal.alert(
          '提示',
          '确认下载附件？推荐安装使用Wps Office打开预览附件？',
          [
            {
              text: '取消',
              // onPress: () => console.log('cancel'),
              style: 'cancel',
            },
            {
              text: '安装Wps',
              onPress: () => {
                Linking.openURL('https://hoplink.wps.cn/s/OBj6uY29T');
              },
              style: 'cancel',
            },
            {
              text: '直接下载',
              onPress: () => {
                ToastUtil.info('附件下载中...', null, 1);
                NativeModules.DownloadFile.downloading(url, name, name);
              },
            },
          ],
        );
      } else {
        // return Linking.openURL('https://www.kdocs.cn/welcome?channel=1005')
        Modal.alert('提示', '确认下载并打开附件？', [
          {
            text: '取消',
            // onPress: () => console.log('cancel'),
            style: 'cancel',
          },
          {
            text: '确认',
            onPress: () => {
              ToastUtil.info('附件下载中...', null, 1);
              NativeModules.DownloadFile.downloading(url, name, name);
            },
          },
        ]);
        // console.log(name);
        // NativeModules.DownloadFile.downloading(url, name, name);
      }
      // NativeModules.DownloadFile.downloading(url, name, name);
    });

    // Linking.canOpenURL(url)
    //   .then((supported) => {
    //     if (!supported) {
    //       ToastUtil.info('请先下载浏览器');
    //     } else {
    //
    //     }
    //   })
    //   .catch(() => ToastUtil.info('打开文章链接失败'));
  }
  // static getUserInfo() {
  //   return new Promise((resolve, reject) => {
  //     const url = BASE_URL.apiBaseUrl + '/user/current';
  //     HttpUtils.get(url)
  //       .then((result) => {
  //         resolve(result);
  //       })
  //       .catch((e) => {
  //         reject(e);
  //       });
  //   });
  // }
  // 获取身份证的出生日期
  static getBirthdayFromIdCard(idCard = '') {
    let birthday = '';
    if (idCard != null && idCard !== '') {
      if (idCard.length === 15) {
        birthday = '19' + idCard.substr(6, 6);
      } else if (idCard.length === 18) {
        birthday = idCard.substr(6, 8);
      }
      birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-');
    }
    return birthday;
  }

  // static getPositions(){
  //     return new Promise(() => {
  //         /** 获取当前位置信息 */
  //         console.log(navigator.geolocation)
  //         navigator.geolocation.getCurrentPosition(
  //             location => {
  //                 const longitude = location.coords.longitude//经度
  //                 const latitude = location.coords.latitude//纬度
  //                 //通过调用高德地图逆地理接口，传入经纬度获取位置信息
  //                 fetch(`http://restapi.amap.com/v3/geocode/regeo?
  //                 key=97c933e33025b3843b40016900074704&location=${longitude},${latitude}
  //                 &radius=1000&extensions=all&batch=false&roadlevel=0`, {
  //                     method: "POST",
  //                     headers: {
  //                         "Content-Type": "application/x-www-form-urlencoded"
  //                     },
  //                     body: ``
  //                 })
  //                     .then((response) => response.json())
  //                     .then((jsonData) => {
  //                         // console.log(jsonData)
  //                         try {
  //                             // this.setState({
  //                             //     city: jsonData.regeocode.addressComponent.city,
  //                             //     district: jsonData.regeocode.addressComponent.district,
  //                             //     street: jsonData.regeocode.addressComponent.township,
  //                             //     position: jsonData.regeocode.formatted_address,
  //                             // });
  //                             return jsonData
  //                         } catch (e) {
  //                           return null
  //                         }
  //                     })
  //                     .catch((error) => {
  //                         console.error(error);
  //                         return null
  //                     });
  //             },
  //             error => {
  //                 console.error(error);
  //                 return null
  //             }
  //         );
  //     })
  // }

    /**
   *  分页加载中提示
   */
  static renderRefreshControl(
    title = '加载中',
    isLoading = false,
    refresh = null,
  ) {
    return (
      <RefreshControl
        title={title}
        refreshing={isLoading}
        titleColor={StylesConstant.refreshControlColor}
        colors={[StylesConstant.refreshControlColor]}
        onRefresh={() => refresh && refresh()}
      />
    );
  }

  /**
   * 分页底部加载更多提示
   */
  static renderLoadingMore() {
    return (
      <View style={GlobalStyles.indicatorContainer}>
        <ActivityIndicator
          color={StylesConstant.refreshControlColor}
          style={GlobalStyles.indicator}
        />
        <Text style={GlobalStyles.indicatorText}>正在加载更多</Text>
      </View>
    );
  }

  /**
   * 分页底部没有更多数据提示
   * @returns {*}
   */
  static renderNoDataBottom(styles) {
    return (
      <View
        style={{justifyContent: 'center', alignItems: 'center', marginTop: 20}}>
        <Text style={{color: '#999', ...styles}}>没有更多数据了</Text>
      </View>
    );
  }

  static getRandomString(len = 32) {
    const $chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefhijkmnprstuvwxyz1234567890';
    const maxPos = $chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
  }

  /**
   * 检查timestamp是否在有效期内
   * @param timestamp 项目更新时间
   * @return {boolean} true 不需要更新,false需要更新
   */
  static checkTimestampValid(timestamp) {
    const currentDate = new Date();
    const targetDate = new Date();
    targetDate.setTime(timestamp);
    if (currentDate.getMonth() !== targetDate.getMonth()) {
      return false;
    }
    if (currentDate.getDate() !== targetDate.getDate()) {
      return false;
    }
    if (currentDate.getHours() !== targetDate.getHours()) {
      return false;
    }
    if (currentDate.getMinutes() - targetDate.getMinutes() > 10) {
      return false;
    } //有效期10个分钟
    return true;
  }

  //请求权限
  static async requestMultiplePermission(toast, uploadPath, version) {
    try {
      const permissions = [
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.CAMERA,
      ];
      //返回得是对象类型
      const granteds = await PermissionsAndroid.requestMultiple(permissions);
      if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted'&&
          granteds['android.permission.READ_EXTERNAL_STORAGE'] === 'granted'&&
          granteds['android.permission.CAMERA'] === 'granted'
      ) {
        // toast.show('开始下载...');
        ToastUtil.info('开始下载...', null, 1, false);
        // this.updateApp(toast, uploadPath, version);
        NativeModules.DownloadApk.downloading(
          uploadPath,
          'safe_' + version,
          'safe_' + version,
        );
      } else {
        ToastUtil.info('用户取消授权,请重试', null, 1, false);
        // toast.show('用户取消授权,请重试');
      }
    } catch (err) {
      // toast.show(err.toString());
      ToastUtil.info(err.toString(), null, 1, false);
    }
  }

  static updateApp(toast, uploadPath, version) {
    //
    let dirs = RNFetchBlob.fs.dirs;
    let android = RNFetchBlob.android;
    RNFetchBlob.config({
      addAndroidDownloads: {
        // 调起原生下载管理
        useDownloadManager: true,
        // 你想要设置的下载的安装包保存的名字
        title: `safe_${version}.apk`,
        // 下载时候顶部通知栏的描述
        description: '下载完成之后将会自动安装',
        // 下载的文件格式
        mime: 'application/vnd.android.package-archive',
        // 下载完成之后扫描下载的文件
        mediaScannable: true,
        // 通知栏显示下载情况
        notification: true,
        // 文件下载的同时缓存起来，提高操作效率
        fileCache: true,
        path: dirs.DownloadDir + `/safe_${version}.apk`,
      },
    })
      .fetch('GET', uploadPath)
      .progress((received, total) => {
        // todo：貌似下载进度无法响应
        // console.log('下载进度：' + Math.floor((received / total) * 100) + '%');
      })
      .then((res) => {
        android.actionViewIntent(
          dirs.DownloadDir + `/safe_${version}.apk`,
          'application/vnd.android.package-archive',
        );
      })
      .catch((err) => {
        // toast.show('下载失败');
        ToastUtil.info('下载失败');
        // console.warn(err);
      });
  }
}
